#include "arg_parse.h"

int arg_parse_init( int argc, char **argv )
{
	int index,opt,i;
	
	cmd_args.ifile = FALSE;
	cmd_args.ifile_name = NULL;
	cmd_args.ofile = FALSE;
	cmd_args.ofile_name = NULL;
	cmd_args.binf = FALSE;
	cmd_args.binf_name = NULL;
	cmd_args.ifmt = NULL;
	cmd_args.ifmt = NULL;
	cmd_args.help = FALSE;
	
	//parse options
	while ((opt = getopt_long(argc, argv, cmd_args_short, cmd_args_long, &index)) != -1)
	//while ((opt = getopt(argc, argv, cmd_arg_short)) != -1)
	{
		if ( opt == -1 ) break;
		switch ( opt )
		{
			case '?':
			case 'h':
				cmd_args.help = TRUE;
				break;
			case 'i':
				cmd_args.ifile = TRUE;
				cmd_args.ifile_name = optarg;
				break;
			case 'o':
				cmd_args.ofile = TRUE;
				cmd_args.ofile_name = optarg;
				break;
			case 'f':
				cmd_args.binf = TRUE;
				cmd_args.binf_name = optarg;
				break;
			default:
				exit(EXIT_FAILURE);
		}
	}

	if ( cmd_args.help )
	{
		print_help();
		exit(1);
	}
	
	if ( cmd_args.binf != TRUE )
	{
		printf("I whanna format\n");
		exit(1);
	}

	if ( cmd_args.ifile_name == NULL )
	{
		printf("I whanna input file\n");
		exit(1);
	}

	if ( cmd_args.ofile_name == NULL )
	{
		printf("I whanna output file\n");
		exit(1);
	}

	{
		char *s=cmd_args.binf_name;
		int s_size = strlen(s);
		for (i=0;i<s_size;i++)
		{
			if ( s[i]=='2' )
			{
				cmd_args.ifmt = malloc( i+1 );
				memcpy( cmd_args.ifmt, s, i );
				cmd_args.ifmt[i]=0;

				cmd_args.ofmt = malloc( s_size-i );
				memcpy( cmd_args.ofmt, &s[i+1], s_size-i-1 );
				cmd_args.ofmt[s_size-i-1]=0;
				break;
			}
		}
		PRINT("IN  format : %s\n", cmd_args.ifmt);
		PRINT("OUT format : %s\n", cmd_args.ofmt);
		PRINT("INPUT file : %s\n", cmd_args.ifile_name);
		PRINT("OUTPUT file: %s\n", cmd_args.ofile_name);
	}

	return 0;
}

int arg_sanity()
{
	//check if input file excist
	//check if output file excist
	//check format name
	return 0;
}

int arg_help()
{
	return cmd_args.help;
}

int   arg_valid_ifmt( char *in )
{
	int i;
	const char *f[] = {"bin",0};
	const int size = (sizeof(f)/sizeof(*f))-1;//who knows
	if ( in != NULL )
	{
		for ( i=0;i<size;i++ )
		{
			if ( strncmp(in, f[i], 3) == 0)
			{
					return 1;
			}
		}
		return 0;
	}
	return 0;
}


int   arg_valid_ofmt( char *out )
{
	int i;
	const char *f[] = {"bin","bit","c","hex","html",0};
	const int size = (sizeof(f)/sizeof(*f))-1;//who knows
	if ( out != NULL )
	{
		for ( i=0;i<size;i++ )
		{
			if ( strncmp(out, f[i], strlen(f[i])) == 0)
			{
				return 1;
			}
		}
		return 0;
	}
	return 0;
}


int print_help()
{
	printf("reprbin [OPTIONS] ... \n \
reprbin version 0.1 convert files from/to different binary file formats\t\n \
\t-i,--input file \t\n\
\t-o,--output file\t\n\
\t-f,--format=[bin2(bin|bit|c|hex|html)]\t\n\
");
	return 0;
}

char* arg_input_file()
{
	return cmd_args.ifile_name;
}


char* arg_output_file()
{
	return cmd_args.ofile_name;
}


char* arg_input_fmt()
{
	return cmd_args.ifmt;
}


char* arg_output_fmt()
{
	return cmd_args.ofmt;
}


